package com.apobates.jforum2.troll.notices;

import com.apobates.jforum2.troll.notices.entity.ForumLetter;
import com.apobates.jforum2.troll.notices.entity.ForumLetterReceiver;
import com.apobates.jforum2.troll.notices.entity.ForumLetterStatus;
import com.apobates.jforum2.troll.notices.entity.ForumLetterTypeEnum;

import java.time.LocalDateTime;
import java.util.HashSet;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;

public class ForumLetterReplica{
    private Set<ForumLetterReceiver> receivers = new HashSet<>();
    //Inbox的状态{readable|reply|usable}
    private ForumLetterStatus status;
    //消息
    private ForumLetter letter;

    public ForumLetterReplica() {
    }

    public ForumLetterReplica(ForumLetter letter){
        this.letter = letter;
    }

    public Set<ForumLetterReceiver> getReceivers() {
        return receivers;
    }

    public void setReceivers(Set<ForumLetterReceiver> receivers) {
        this.receivers = receivers;
    }

    public ForumLetterStatus getStatus() {
        return status;
    }

    public void setStatus(ForumLetterStatus status) {
        this.status = status;
    }

    public void setLetter(ForumLetter letter) {
        this.letter = letter;
    }

    public ForumLetter getLetter() {
        return letter;
    }

    //委托实现
    public long getId() {
        return Optional.of(letter).map(ForumLetter::getId).orElse(0L);
    }
    public String getTitle(){
        return Optional.of(letter).map(ForumLetter::getTitle).orElse("一条消息");
    }
    public String getContent(){
        return Optional.of(letter).map(ForumLetter::getContent).orElse("");
    }
    public LocalDateTime getEntryDateTime(){
        return Optional.of(letter).map(ForumLetter::getEntryDateTime).orElse(LocalDateTime.now());
    }
    public ForumLetterTypeEnum getTyped(){
        return Optional.of(letter).map(ForumLetter::getTyped).orElse(ForumLetterTypeEnum.ALL);
    }
    public String getTargetReceiverNicknames() {
        if (getReceivers().isEmpty()) {
            return ForumLetterTypeEnum.ALL.getTitle();
        }
        return getReceivers().stream().map(ForumLetterReceiver::getMemberNickname).collect(Collectors.joining(","));
    }
    /**
     * 输出事件需要的ForumLetter实例
     * @return
     */
    public ForumLetter toEventPayload(){
        ForumLetter fl = new ForumLetter();
        fl.setId(getLetter().getId());
        fl.setNickname(getLetter().getNickname());
        fl.setAuthor(getLetter().getAuthor());
        return fl;
    }
}
